package com.ruoyi.common.utils;

import com.ruoyi.common.core.exception.CustomException;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Objects;

/**
 * 税率计算工具类
 */
public class TaxRateUtil {
    /**
     * 计算综合税率 [（增值税税率+消费税税率 ）/ (1-消费税税率) ] x 70%
     *
     * @param valueAddedTaxRate  增值税
     * @param consumptionTaxRate 消费税
     * @return
     */
    public static BigDecimal calcTaxRate(BigDecimal valueAddedTaxRate, BigDecimal consumptionTaxRate) {
        if (Objects.isNull(valueAddedTaxRate) || Objects.isNull(consumptionTaxRate)) {
            throw new CustomException("增值税或消费税不能为空");
        }

        return valueAddedTaxRate.add(consumptionTaxRate)
                .divide(BigDecimal.ONE.subtract(consumptionTaxRate),4,BigDecimal.ROUND_HALF_UP)
                .multiply(new BigDecimal(0.7)).setScale(3, BigDecimal.ROUND_HALF_UP);
    }

    /**
     * 计算综合税率
     *
     * @param valueAddedTaxRate 增值税
     * @return
     */
    public static BigDecimal calcTaxRate(BigDecimal valueAddedTaxRate) {
        if (Objects.isNull(valueAddedTaxRate)) {
            throw new CustomException("增值税不能为空");
        }
        return calcTaxRate(valueAddedTaxRate, BigDecimal.ZERO);
    }

    /**
     * 计算税额 （金额含税）
     * @param goodsAmount
     * @param taxRate
     * @return
     */
    public static BigDecimal calculateTaxAmountIncludeTax(BigDecimal goodsAmount, BigDecimal taxRate) {
        AssertUtils.notNull(goodsAmount,"销售金额必填");
        AssertUtils.notNull(taxRate,"税率必填");
        BigDecimal includeTaxRate = BigDecimal.ONE.add(taxRate);
        return goodsAmount.divide(includeTaxRate, 6, RoundingMode.HALF_UP).multiply(taxRate).setScale(2, RoundingMode.HALF_UP);
    }

    /**
     * 计算税额 （金额不含税）
     * @param goodsAmount
     * @param taxRate
     * @return
     */
    public static BigDecimal calculateTaxAmountNotIncludeTax(BigDecimal goodsAmount, BigDecimal taxRate) {
        AssertUtils.notNull(goodsAmount,"销售金额必填");
        AssertUtils.notNull(taxRate,"税率必填");
        return goodsAmount.multiply(taxRate).setScale(2, RoundingMode.HALF_UP);
    }
}
